﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Script.Serialization;

namespace FxSuperCore.Log
{
	public class SimpleLogFormatter : ILogFormat
	{
		public string FormatObject(object msg)
		{
			if (msg == null)
			{
				return "null";
			}

			if (msg.GetType() == typeof(byte[]))
			{
				byte[] bytes = (byte[])msg;
				msg = bytes.Select(b => Convert.ToInt32(b)).ToList();
			}

			string msgRes = msg.ToString();
			Type type = msg.GetType();

			if (msg is Array || msg is IDictionary<string, object> || type.IsGenericType
			    || typeof(IEnumerable<>).IsAssignableFrom(type))
			{
				try
				{
					JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
					msgRes = javaScriptSerializer.Serialize(msg);
				}
				catch (Exception) { /*ignore*/ }
			}

			return msgRes;
		}
	}
}
